package cn.mazexal.examapi.controller.notify;

import cn.hutool.core.convert.Convert;
import cn.mazexal.examapi.common.anno.PermitGuest;
import cn.mazexal.examapi.models.bo.PayNotify;
import cn.mazexal.examapi.models.thirdpart.alipay.AlipayTradeStatus;
import cn.mazexal.examapi.services.OrderService;
import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Map;

/**
 * @author: Mazexal
 * Date: 2025/6/30
 */
@RestController
@Tag(name = "notify", description = "回调")
@RequestMapping("/notify/ali")
@Slf4j
public class AliNotifyController {

    private static final String aliFail = "fail";
    private static final String aliSuccess = "success";


    @Resource
    private HttpServletRequest request;
    @Autowired
    private OrderService orderService;


    @PostMapping("/aliPayNotify")
    @PermitGuest
    public String aliPayNotify(@RequestParam Map<String, String> params) {
        // todo
        log.info("支付宝异步通知 {}", JSON.toJSONString(params));

        boolean signVerified = verifySignature(params);
        if (!signVerified) {
            log.error("支付宝异步通知验签失败");
            return aliFail; // 验签失败
        }

        String tradeStatus = params.get("trade_status");
        if (AlipayTradeStatus.TRADE_SUCCESS.equals(tradeStatus)) {
            // 支付成功，更新订单状态

            PayNotify payNotify = new PayNotify();
            payNotify.setPayId(Convert.toLong(params.get("out_trade_no")));
            payNotify.setBuyerId(params.get("buyer_id"));
            payNotify.setBuyerAccount(params.get("buyer_logon_id"));
            payNotify.setSellerId(params.get("seller_id"));
            payNotify.setSellerAccount(params.get("seller_id"));
            payNotify.setTotalAmount(new BigDecimal(params.get("total_amount")));
            payNotify.setNotifyId(params.get("notify_id"));

            try {
                orderService.handlePayNotify(payNotify);
            } catch (Exception e) {
                log.error("支付宝异步通知处理失败", e);
                return aliFail;
            }
//            updateOrderStatus(outTradeNo, tradeNo); // 自定义业务方法
        }

        return aliSuccess;
    }

    private boolean verifySignature(Map<String, String> params) {
        try {
            return AlipaySignature.rsaCheckV1(
                    params,
                    "支付宝公钥", // 从开放平台获取
                    "UTF-8",
                    "RSA2" // 签名算法
            );
        } catch (AlipayApiException e) {
            return false;
        }
    }
}
